﻿Imports System
Imports System.Net
Imports System.IO
Public Class Springnote
    Public strUserName As String
    Public strUserKey As String

    Public Sub New(ByVal userName As String, ByVal userKey As String)

        strUserName = userName
        strUserKey = userKey

    End Sub

    Public Function Auth() As String

        Dim strAppKey As String = "AppKey"
        Dim strAppId As String = "AppId"
        Dim strUserNameURI As New Uri(Me.strUserName)

        Dim strNonce As String = Util.getRandomHexCodeString(16)

        Dim utcNow As DateTime = DateTime.UtcNow
        Dim strCreated As String = Format(utcNow, "yyyy-MM-dd'T'HH:mm:ss'Z'")

        Dim i As Integer
        Dim encoding As New System.Text.ASCIIEncoding()

        Dim strKeyDigester As System.Security.Cryptography.SHA1
        strKeyDigester = System.Security.Cryptography.SHA1.Create()

        Dim strConvertToByte As Byte() = encoding.GetBytes(strNonce & strCreated & Me.strUserKey & strAppKey)

        Dim strKeyDigest As Byte() = strKeyDigester.ComputeHash(strConvertToByte)

        Dim tmpTextStr As String = ""

        For i = 0 To strKeyDigest.Length - 1

            tmpTextStr += Format(Conversion.Hex(strKeyDigest.GetValue(i)).ToLower, "{0,2:X}").Replace(" ", "0")

        Next

        Dim strPassword As String = Uri.EscapeDataString(strAppId & "," & strNonce & "," & strCreated & "," & tmpTextStr)

        Dim ret As String = Uri.EscapeDataString(strUserName.ToString) & ":" & strPassword

        Return Util.Base64Encode(ret, Text.Encoding.GetEncoding("ASCII"))

    End Function

    Public Function GetPage(ByVal strUrl As String) As String

        Dim strWebclient As New WebClient
        strWebclient.Headers.Add("Authorization", "Basic " & Me.Auth())

        Dim strMoveUrl As New Uri(strUrl)
        Dim data As Stream = strWebclient.OpenRead(strMoveUrl)

        Dim reader As New StreamReader(data)

        Return reader.ReadToEnd()

    End Function

End Class
